package com.yoyo.yyadsdk.activity;


import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;

import com.bumptech.glide.Glide;
import com.dollkey.hdownload.activity.AdWebViewActivity;
import com.qq.e.ads.nativ.widget.NativeAdContainer;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.yoyo.ad.contract.AdContract;
import com.yoyo.ad.main.AdModelType;
import com.yoyo.ad.main.IAdFactory;
import com.yoyo.ad.main.IAdView;
import com.yoyo.ad.main.YoYoAd;
import com.yoyo.ad.main.YoYoAdManager;
import com.yoyo.ad.utils.StringUtil;
import com.yoyo.yyadsdk.R;
import com.yoyo.yyadsdk.api.IConfigApi;
import com.yoyo.yyadsdk.bean.DayWordBean;
import com.yoyo.yyadsdk.bean.dao.AdvScreenEntity;
import com.yoyo.yyadsdk.config.Constants;
import com.yoyo.yyadsdk.config.PullFeature;
import com.yoyo.yyadsdk.util.AdvUtils;
import com.yoyo.yyadsdk.util.AnalysisUtils;
import com.yoyo.yyadsdk.util.ApiManage;
import com.yoyo.yyadsdk.util.LogHelper;
import com.yoyo.yyadsdk.util.TimeUtils;
import com.yoyo.yyadsdk.widget.LockBackgroundView_;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.yoyo.yyadsdk.config.Constants.LOCK_BIG_;
import static com.yoyo.yyadsdk.config.Constants.SUCCESS;
import static com.yoyo.yyadsdk.config.Constants.TYPE_MOULD;


public class LockActivity_ extends AppCompatActivity {

    private static final String TAG = "LockActivity";
    private RelativeLayout mBannerContainer;
    //    private NativeAdContainer mNativeAdContainer;
    private FrameLayout mNativeAdContainer;
    private RelativeLayout mContentContains;
    private Context mContext;
    protected int mWidth;
    protected int mHeight;
    private IAdFactory mAdFactory;
    private TextView mTimeTv;
    private TextView mDateTv;

    private TextView mDescribeTv;
    private ImageView mAdImageIv;
    private FrameLayout mVideoFv;
    private ImageView mIconIv;
    private TextView mSourceTv;
    private ImageView mLogo;

    private YoYoAd mYoYoAd;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private DayWordBean.RespDataBean mRespData;

    public static void launch(Context context, AdvScreenEntity advScreen) {
        if (context != null && advScreen != null)
            context.startActivity(new Intent(context, LockActivity_.class)
                    .putExtra("advEntity", advScreen)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //四个标志位顾名思义，分别是锁屏状态下显示，解锁，保持屏幕长亮，打开屏幕。这样当Activity启动的时候，它会解锁并亮屏显示。
        beforeInit();
        setContentView(R.layout.activity_lock_native);
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        mWidth = outMetrics.widthPixels;
        mHeight = outMetrics.heightPixels;
        mContext = this;
        mBannerContainer = findViewById(R.id.banner_contains);
        mNativeAdContainer = findViewById(R.id.native_ad_container);
        mContentContains = findViewById(R.id.content_contains);
        mTimeTv = findViewById(R.id.time_tv);
        mDateTv = findViewById(R.id.date_tv);

        mDescribeTv = findViewById(R.id.tv_listitem_ad_desc);
        mAdImageIv = findViewById(R.id.iv_listitem_image);
        mVideoFv = findViewById(R.id.iv_listitem_video);
        mIconIv = findViewById(R.id.iv_listitem_icon);
        mSourceTv = findViewById(R.id.tv_listitem_ad_source);
        mLogo = findViewById(R.id.iv_listitem_logo);
        findViewById(R.id.iv_listitem_dislike).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        mContentContains.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                containClick();
            }
        });
        mDateTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                containClick();
            }
        });
        mTimeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                containClick();
            }
        });
        LockBackgroundView_ parent = findViewById(R.id.parent);
        parent.setSwipeBackListener(new LockBackgroundView_.SwipeBackFinishActivityListener(this));
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTimeTv.setText(TimeUtils.getTime());
                        Calendar calendar = Calendar.getInstance(Locale.getDefault());
                        calendar.setTime(new Date());
                        int week = calendar.get(Calendar.DAY_OF_WEEK);
                        mDateTv.setText(TimeUtils.getWeek(week).concat("  ").concat(TimeUtils.getDate()));
                    }
                });
            }
        };
        mTimer.schedule(mTimerTask, 0, 5 * TimeUtils.SECOND);

        loadAd();
        loadDayWord();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AdvScreenEntity advEntity = getIntent().getParcelableExtra("advEntity");
                AdvUtils.recordAdvExposed(advEntity.getId(), PullFeature.ADV_LOCK_SCREEN);
            }
        }, 500);
    }

    protected void containClick() {
        if (mRespData != null) {
            if (mRespData.getType() == 1)
//                AdWebViewActivity.toBrowser(mContext, "https://today.ttlaosiji.cn/?qid=L11&?ADTAG=kp.sp");
                AdWebViewActivity.newInstance(mContext, "https://today.ttlaosiji.cn/?qid=L11&?ADTAG=kp.sp", false);
            else {
//                AdWebViewActivity.toBrowser(mContext, mRespData.getToUrl());
                AdWebViewActivity.newInstance(mContext, mRespData.getToUrl(), mRespData.getType(), AnalysisUtils.POSITION_LOCK, mRespData.getContentId(), false);
                AnalysisUtils.addStatistics(mContext, mRespData.getType(), AnalysisUtils.POSITION_LOCK, AnalysisUtils.TYPE_CLICK, mRespData.getContentId());
            }
        }
    }

//    private long currentTimeMillis;

    private void loadAd() {
        mAdFactory = YoYoAdManager.getAdFactory(mContext, new IAdView() {

            @Override
            public void adSuccess(int requestCode, List<YoYoAd> t) {
                if (t != null && t.size() > 0) {
                    if (mYoYoAd != null) {
                        mYoYoAd.release();
                    }
                    mNativeAdContainer.setVisibility(View.VISIBLE);
                    mYoYoAd = t.get(0);
                    if (mYoYoAd.isNativeExpress()) {
                        mYoYoAd.exposure(null);
                        mBannerContainer.setVisibility(View.GONE);
                        mNativeAdContainer.addView(mYoYoAd.getView());
                    } else {
                        if (mNativeAdContainer.getChildCount() > 1) {
                            mNativeAdContainer.removeViewAt(1);
                        }
                        mBannerContainer.setVisibility(View.VISIBLE);
                        mDescribeTv.setText(mYoYoAd.getDescription());
                        mSourceTv.setText(mYoYoAd.getTitle());
                        if (!StringUtil.isNull(mYoYoAd.getIconUrl())) {
                            Glide.with(mIconIv).load(mYoYoAd.getIconUrl()).into(mIconIv);
                            mIconIv.setVisibility(View.VISIBLE);
                        } else {
                            mIconIv.setVisibility(View.GONE);
                        }
                        if (mYoYoAd.getLogo() != null) {
                            mLogo.setImageBitmap(mYoYoAd.getLogo());
                        }
                        mVideoFv.removeAllViews();
                        if (mYoYoAd.getModel() == AdModelType.MODEL_IMAGE) {
                            Glide.with(mAdImageIv).load(mYoYoAd.getImgUrl1()).into(mAdImageIv);
                            mYoYoAd.onAdClicked(mBannerContainer, mNativeAdContainer);
                            mYoYoAd.exposure(mNativeAdContainer);
                        } else if (mYoYoAd.getModel() == AdModelType.MODEL_VIDEO) {
                            if (mYoYoAd.getView() != null) {
                                mVideoFv.addView(mYoYoAd.getView());
                            }
                            mYoYoAd.onAdClicked(mVideoFv, mNativeAdContainer);
                        }
                    }
                } else {
                    mNativeAdContainer.setVisibility(View.GONE);
                }
//                Log.e(TAG, "end:" + System.currentTimeMillis());
//                Log.e(TAG, "differ:" + (currentTimeMillis - System.currentTimeMillis()));
            }

            @Override
            public void adFail(int requestCode, String arg0) {
//                Log.e(TAG, "end:" + System.currentTimeMillis());
//                Log.e(TAG, "differ:" + (currentTimeMillis - System.currentTimeMillis()));
//                Log.e(TAG, "error:" + arg0);
                LogHelper.e(arg0);
//                finish();
            }

            @Override
            public void onAdClick(int requestCode, View view) {

            }
        });
        YoYoAdManager.getConfig(mContext, new AdContract.View() {
            @Override
            public void onAdSuccess() {
//                currentTimeMillis = System.currentTimeMillis();
//                Log.e(TAG, "start:" + currentTimeMillis);
                mAdFactory.getYoyoAd(LOCK_BIG_, 1, 3, TYPE_MOULD);
            }

            @Override
            public void onAdFail(String err) {
                finish();
            }
        });
    }

    private void loadDayWord() {
        ApiManage.getInstance().getApi("https://lock.ttlaosiji.cn:8082/", IConfigApi.class)
                .getDayWord(Constants.MEDIA_ID)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .as(AutoDispose.<DayWordBean>autoDisposable(AndroidLifecycleScopeProvider
                        .from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new Consumer<DayWordBean>() {
                    @Override
                    public void accept(DayWordBean updateBean) {
                        if (updateBean.getResp_status().equals(SUCCESS)) {
                            TextView fortuneTv;
                            TextView wordTv;
                            TextView authorTv;
                            TextView newsDateTv;
                            TextView sourceTv;
                            ImageView newsIv;
                            mRespData = updateBean.getResp_data();
                            switch (mRespData.getType()) {
                                case 1: //每日一言
                                    ((ViewStub) findViewById(R.id.day_word_item)).inflate();
                                    fortuneTv = findViewById(R.id.fortune_tv);
                                    wordTv = findViewById(R.id.word_tv);
                                    authorTv = findViewById(R.id.author_tv);

                                    fortuneTv.setText(mRespData.getDayWord().getFortune());
                                    wordTv.setText(mRespData.getDayWord().getWord());
                                    authorTv.setText("- - ".concat(mRespData.getDayWord().getAuthor()));
                                    break;
                                case 2: //历史上的今天
                                    ((ViewStub) findViewById(R.id.history_item)).inflate();
                                    wordTv = findViewById(R.id.word_tv);
                                    newsDateTv = findViewById(R.id.news_date_tv);

                                    String[] title = mRespData.getTitle().split(" ");
                                    wordTv.setText(title[1]);
                                    newsDateTv.setText(title[0]);
                                    break;
                                case 3: //新闻
                                case 4: //视频
                                    ((ViewStub) findViewById(R.id.news_item)).inflate();
                                    newsIv = findViewById(R.id.news_iv);
                                    sourceTv = findViewById(R.id.source_tv);
                                    wordTv = findViewById(R.id.word_tv);
                                    Glide.with(newsIv).load(mRespData.getCover()).into(newsIv);
                                    wordTv.setText(mRespData.getTitle());
                                    sourceTv.setText(mRespData.getSource());
                                    break;
                            }
                            AnalysisUtils.addStatistics(mContext, mRespData.getType(), AnalysisUtils.POSITION_LOCK, AnalysisUtils.TYPE_LOAD, mRespData.getContentId());
                            findViewById(R.id.play_iv).setVisibility(mRespData.getType() == 4 ? View.VISIBLE : View.GONE);
                            mContentContains.setVisibility(View.VISIBLE);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                    }
                });
    }

//    private File cameraSavePath;//拍照照片路径
//    private Uri uri;//照片uri
//
//    //激活相机操作
//    private void goCamera() {
//        cameraSavePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
//                .concat(File.separator)
//                .concat(Environment.DIRECTORY_DCIM), System.currentTimeMillis() + ".jpg");
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            //第二个参数为 包名.fileprovider
//            uri = FileProvider.getUriForFile(LockActivity_.this, getApplicationInfo().processName.concat(".fileprovider"), cameraSavePath);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        } else {
//            uri = Uri.fromFile(cameraSavePath);
//        }
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//        startActivityForResult(intent, 1);
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAdFactory.destroy();
        if (mYoYoAd != null) {
            mYoYoAd.release();
            mYoYoAd = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
        }
    }

    private void beforeInit() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED //锁屏状态下显示
//                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD //解锁
//                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON //保持屏幕长亮
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); //打开屏幕
        Drawable wallPaper = WallpaperManager.getInstance(this).getDrawable();
        window.setBackgroundDrawable(wallPaper);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | (isDarkThemeStatusBar() ? View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR : View.SYSTEM_UI_FLAG_LAYOUT_STABLE));
            } else {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    public void onBackPressed() {
    }

    public void close(View v) {
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.activity_out);
    }
}
